package com.boe.csb.core.service.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.boe.csb.core.common.status.CommonStatus;
import com.boe.csb.core.dao.BoeApiInfoCriteria;
import com.boe.csb.core.dao.BoeApiInfoMapper;
import com.boe.csb.core.dao.BoeApiPopularCriteria;
import com.boe.csb.core.dao.BoeApiPopularMapper;
import com.boe.csb.core.entity.po.BoeApiInfo;
import com.boe.csb.core.entity.po.BoeApiPopular;
import org.springframework.util.CollectionUtils;


/**
 * Created by tianxiang.luo on 16/11/24.
 */

@Service("boeApiPopularService")
public class BoeApiPopularService {

	private static final Logger logger = LoggerFactory.getLogger(BoeApiPopularService.class);

	private static int RECOMMAND_LIMIT = 6;

    @Autowired
    private BoeApiPopularMapper boeApiPopularMapper;

    @Autowired
    private BoeApiInfoMapper boeApiInfoMapper;

    @Autowired
    private BoeApiInfoService boeApiInfoService;



    /**
     * 查询热门的服务
     */
    public List<BoeApiInfo> queryPopularBoeApiList(int pageNum,int limit){
        BoeApiPopularCriteria criteria = new BoeApiPopularCriteria();
        criteria.createCriteria().andStatusEqualTo(CommonStatus.NORMAL.getStatus());
        criteria.setOrderByClause("subscribe_count desc");
        List<BoeApiPopular> boeApiPopularList = boeApiPopularMapper.selectByExampleWithRowbounds(criteria,new RowBounds((pageNum-1)*limit,limit));
        //存apiList方便后面查询
        List<Long> apiList = new ArrayList<>();
        for(BoeApiPopular boeApiPopular:boeApiPopularList){
            apiList.add(boeApiPopular.getCsbApiId());
        }
        BoeApiInfoCriteria boeApiInfoCriteria = new BoeApiInfoCriteria();
        if(!CollectionUtils.isEmpty(apiList)){
            boeApiInfoCriteria.createCriteria().andCsbApiIdIn(apiList);
            List<BoeApiInfo> infos =  boeApiInfoMapper.selectByExample(boeApiInfoCriteria);
            for(BoeApiInfo info:infos){
                info.setApiPic(boeApiInfoService.getImgPathByService(info));
            }
            return infos;
        }else
            return null;
    }

    /**
     * 更新热门服务 ,订单通过的时候使用
     * @param csbIdList
     */
    @Transactional
    public void updatePopularBoeApiList(List<Long> csbIdList){
        Map<Long,Integer> map = new HashMap<>();
        //压缩数据
        for (Long csbId:csbIdList){
            if(!map.containsKey(csbId)){
                map.put(csbId,1);
            }else {
                int count = map.get(csbId);
                map.remove(csbId);
                map.put(csbId,++count);
            }
        }
        List<Long> updateList = new ArrayList<>();
        //取更新纪录 根据csbApiId更新
        for (Long csbId:map.keySet()){
            BoeApiPopularCriteria criteria = new BoeApiPopularCriteria();
            criteria.createCriteria().andCsbApiIdEqualTo(csbId).andStatusEqualTo(CommonStatus.NORMAL.getStatus());
            Integer count = map.get(csbId);
            //更改了 ret = 1
            if(boeApiPopularMapper.updateSubscribeCountByCsbId(csbId,count)!=1){
                updateList.add(csbId);
            }
        }

        //把数据库没有csbId纪录的 添加到数据库
        for (Long csbId:updateList){
            BoeApiPopular popular = new BoeApiPopular();
            popular.setCsbApiId(csbId);
            popular.setSubscribeCount(map.get(csbId));
            popular.setStatus(CommonStatus.NORMAL.getStatus());
            popular.setGmtCreate(new Date());
            popular.setGmtModified(new Date());
            boeApiPopularMapper.insert(popular);
        }
    }


    /**
     * @param status 1 恢复状态  0 停用
     * @param idList
     */
    public void updatePopularServices(boolean status,List<Long> idList){
        BoeApiPopularCriteria criteria = new BoeApiPopularCriteria();
        criteria.createCriteria().andIdIn(idList);
        BoeApiPopular boeApiPopular = new BoeApiPopular();
        String stat = status?CommonStatus.NORMAL.getStatus():CommonStatus.DELETE.getStatus();
        boeApiPopular.setStatus(stat);
        boeApiPopularMapper.updateByExampleSelective(boeApiPopular,criteria);
    }

    /**
     * 获取订阅指定服务的数量
     * @param apiId
     * @return
     */
    public int getSubscribeCount(Long apiId){

    	 BoeApiPopularCriteria criteria = new BoeApiPopularCriteria();
    	 criteria.createCriteria().andCsbApiIdEqualTo(apiId);
    	 List<BoeApiPopular> boeApiList = boeApiPopularMapper.selectByExample(criteria);
    	 if(boeApiList.size() == 0){
    		 logger.error("can not find apiid:{} from table 'boe_api_popular', please check it!!!", apiId);
    		 return 0;
    	 }

    	 if(boeApiList.size() > 1){
    		 logger.error("get row by apiid:{} from table 'boe_api_popular' result more then one. please check it!!!", apiId);
    	 }
    	 BoeApiPopular apiPopular = boeApiList.get(0);

    	 return apiPopular.getSubscribeCount();
    }



}
